'''
Author: cw
Date: 2025-07-11
Description: ...
'''
import hashlib
from datetime import datetime

from fastapi import Request
from fastapi.responses import PlainTextResponse

from fapi import env

from main import app
from modules import wx_mgr


@app.get('/ping')
async def ping():
    """ping"""
    return {
      "now": datetime.now().strftime('%d/%m/%Y, %H:%M:%S'),
      'env': env.get('NAME')
    }


# 微信消息处理
@app.get("/{appid}/wechat")
async def wechat_verify(
    appid: str,
    signature: str,
    timestamp: str,
    nonce: str,
    echostr: str
):
    """微信服务器验证接口"""
    # 按字典序排序
    lst = [env.WECHAT_TOKEN, timestamp, nonce]
    lst.sort()
    s = ''.join(lst)
    # 计算SHA1加密
    sha1 = hashlib.sha1()
    sha1.update(s.encode('utf-8'))
    hashcode = sha1.hexdigest()
    # 验证签名
    if hashcode == signature:
        print(f"签名验证成功，返回echostr: {echostr}")
        return int(echostr) or 'scuess'
    else:
        return "验证失败"


@app.post("/{appid}/wechat")
async def wechat_message(appid:str, request: Request):
    """处理微信服务器发来的消息"""
    xml_data = await request.body()
    xml_result = await wx_mgr.parse_wechat_message(appid, xml_data)
    return PlainTextResponse(
        content=xml_result,
        media_type="text/xml; charset=utf-8"  # 必须指定，否则默认是text/plain
    )
